<template>
  <div class="app-container org">
    <el-card>
      <el-row>
        <el-col :span="24">
          <p class="pinformation">搜索条件</p>
        </el-col>
      </el-row>
      <el-form ref="queryRef" label-width="100" :model="queryParams">
        <el-row>
          <el-col :span="3">
            <el-form-item label="自制样品名称：" prop="sampleName">
              <el-input clearable maxlength="100" placeholder="请输入自制样品名称" v-model="queryParams.sampleName"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="唯一性编号：" prop="sampleCode">
              <el-input clearable maxlength="100" placeholder="请输入唯一性编号" v-model="queryParams.sampleCode"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="配置人：" prop="selfAdminId" label-width="65">
              <el-select v-model="queryParams.selfAdminId" clearable filterable>
                <el-option v-for="item in proxy.addListNoLimit(
                  userList,
                  'userId',
                  'nickName'
                )" :key="item.userId" :value="item.userId" :label="item.nickName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="配置日期：" prop="" label-width="80">
              <el-date-picker value-format="YYYY-MM-DD" type="daterange" v-model="dateRange" range-separator="-"
                start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="检测项目：" prop="bucketId" label-width="80">
              <el-select v-model="queryParams.bucketId" clearable filterable remote reserve-keyword remote-show-suffix
                :remote-method="remoteMethod" :loading="loading" style="width: 100%">
                <el-option v-for="item in jcxmList" :key="item.bucketId" :value="item.bucketId" :label="item.jcxmName">
                  <span v-html="transformation(item.jcxmName)"></span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="检测项目类型：" prop="isSingle">
              <el-select placeholder="请选择" clearable v-model="queryParams.isSingle" filterable>
                <el-option v-for="dict in proxy.addListNoLimit(sys_bzwz_jcxm_type)" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3" style="padding-left: 30px">
            <el-row>
              <el-radio label="0" v-model="queryParams.isLike">模糊搜索</el-radio>
              <el-radio label="1" v-model="queryParams.isLike">精准搜索</el-radio>
            </el-row>
          </el-col>
          <el-col :span="2">
            <el-row>
              <el-button type="success" @click="handleQuery">搜索</el-button>
              <el-button class="resetBtn" @click="resetQuery">重置</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <p class="pinformation">自制样品列表</p>
        <p class="totalStyle">共 {{ total }} 条数据</p>
        <el-row style="padding-bottom: 5px; margin-left: 20px">
          <el-button type="success" link icon="Plus" @click="singleAdd">单个入库</el-button>
          <el-button type="success" link icon="Plus" @click="importTemplate">导出数据</el-button>
          <el-button type="success" link icon="Plus">批量入库</el-button>
          <el-button type="success" link icon="Plus" @click="handleExport">导出入库记录</el-button>
          <el-button type="success" style="margin-left: 10px" link icon="Plus" @click="handleImport">导入入库记录</el-button>
        </el-row>
        <el-table ref="mainTableRef" :data="outTable" @selection-change="handleSelChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="唯一性编号" prop="sampleCode" align="center" />
          <el-table-column label="自制样品名称" prop="sampleName" align="center" />
          <el-table-column label="种类" prop="sampleType" align="center">
            <template #default="scope">
              <dict-tag :options="sys_self_sample_type" :value="scope.row.sampleType" />
            </template>
          </el-table-column>
          <el-table-column label="溶剂" prop="rj" align="center">
          </el-table-column>
          <el-table-column label="定容体积" prop="drtj" align="center">
            <template #default="scope">
              <span v-html="scope.row.drtj +
                transformation(scope.row.drtjUnitName)
                "></span>
            </template>
          </el-table-column>
          <el-table-column label="配置日期" prop="createDate" align="center" />
          <el-table-column label="有效日期" prop="yxDate" align="center" />
          <el-table-column label="保存条件" prop="saveCondition" align="center" />
          <el-table-column label="保存位置" prop="saveLocation" align="center" />
          <el-table-column label="配置人" prop="selfAdminId" align="center">
            <template #default="scope">
              {{
                proxy.getItemByArray(
                  userList,
                  "userId",
                  scope.row.selfAdminId,
                  "nickName"
                )
              }}
            </template>
          </el-table-column>
          <el-table-column label="检测项目数" prop="jcxmCount" align="center">
            <template #default="scope">
              <el-button link @click="jcxmCountClick(scope.row.sampleId)">{{
                scope.row.jcxmName ? scope.row.jcxmName : scope.row.jcxmCount
              }}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="181px">
            <template #default="scope">
              <el-button link type="success" @click="xqZzyp(scope.row.sampleId, 1)">引用</el-button>
              <el-button link type="success" @click="xqZzyp(scope.row.sampleId, 3)">编辑</el-button>
              <el-button link type="success" @click="delBzwz(scope.row.sampleId)" v-if="!scope.row.useDrtj">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-row>
    </el-card>
    <!-- 点击行内检测项目数的弹窗 -->
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="jcxmOpen" @close="closedDialog" :title="title">
      <el-row>
        <p class="pinformation">检测项目列表</p>
        <p class="totalStyle">共 {{ multiplexTable.length }} 条数据</p>
      </el-row>
      <el-table :data="multiplexTable">
        <el-table-column label="检测项目" prop="bucketId" align="center">
          <template #default="scope">
            <span v-html="transformation(scope.row.jcxmName)"></span>
          </template>
        </el-table-column>
        <el-table-column label="浓度值" prop="con" align="center" />
        <el-table-column label="浓度值单位" prop="conUnit" align="center">
          <template #default="scope">
            <span v-html="transformation(getConUnitHtml(scope.row.conUnit))"></span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="jcxmOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 单个入库和引用弹窗 -->
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      @close="closedXqDialog" v-model="rkOrYyOpen" :title="rkOrYyTitle" width="1100">
      <el-form label-width="110" ref="rkOrYyRef" :model="form" :rules="rules">
        <el-row>
          <el-col :span="8">
            <el-form-item label="自制样品名称：" prop="sampleName">
              <el-input clearable maxlength="100" v-model="form.sampleName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="唯一性编号：" prop="sampleCode">
              <onlinePreview :typeId="serialTypeId" @emitForm="emitForm" ref="onlinePreviewRef"
                v-if="!form.sampleCode && rkOrYyOpen"></onlinePreview>
              <span v-if="form.sampleCode">{{ form.sampleCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="种类：" prop="sampleType">
              <el-select placeholder="请选择" clearable v-model="form.sampleType" filterable style="width: 100%">
                <el-option v-for="dict in sys_self_sample_type" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库日期：" prop="createDate">
              <el-date-picker v-model="form.createDate" placeholder="请选择要求完成时间" type="date" value-format="YYYY-MM-DD"
                style="width: 100%" :clearable="false" :editable="false" @change="pickerChange" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="有效期：" prop="yxDate">
              <el-date-picker v-model="form.yxDate" placeholder="请选择有效期" type="date" value-format="YYYY-MM-DD"
                style="width: 100%" @change="pickerChange" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="溶剂：" prop="rj">
              <el-input clearable maxlength="100" v-model="form.rj"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-row :gutter="5">
              <el-col :span="15">
                <el-form-item label="定容体积：" prop="drtj">
                  <el-input-number clearable v-model="form.drtj" :disabled="(form.useDrtj ? true : false) && form.useDrtj !== 0
                    " :min="1" style="width: 100%" controls-position="right"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="9">
                <el-form-item label-width="0" prop="drtjUnit">
                  <el-select v-model="form.drtjUnit" placeholder="" clearable filterable>
                    <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName" :value="item.unitId">
                      <span v-html="transformation(item.unitName)"></span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-form-item label="天平编号：" prop="tpCode">
              <el-select v-model="form.tpCode" @change="tpCodeChange" clearable filterable style="width: 100%">
                <el-option v-for="item in tpCodeList" :key="item.instrumentId" :value="item.instrumentId"
                  :label="item.number"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="天平型号：" prop="tpTh">
              {{ form.tpXh }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="保存条件：" prop="saveCondition">
              <el-input clearable maxlength="100" v-model="form.saveCondition"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保存位置：" prop="saveLocation">
              <el-input clearable maxlength="100" v-model="form.saveLocation"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <p class="pinformation">选择参与物质</p>
          <p class="totalStyle">
            共 {{ form.selfSampleBzwzList.length }} 条数据
          </p>
          <el-row style="padding-bottom: 5px; margin-left: 20px">
            <el-button link icon="Plus" @click="handleBzwzList">新增</el-button>
            <el-button link @click="delectBzwzList(a, 1)" :disabled="ids">批量删除</el-button>
          </el-row>
        </el-row>
        <el-table :data="form.selfSampleBzwzList" @selection-change="handleBzwzSelectionChange"
          style="margin-bottom: 10px">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="选择参与物质" prop="outId" align="center" width="180">
            <template #default="scope">
              <el-select v-model="scope.row.outId" placeholder="请选择" clearable filterable @change="outCodeChange(scope)">
                <el-option v-for="item in bzwzList" :key="item.outId" :value="item.outId"
                  :label="item.outCode + '　' + item.name">
                  <el-tooltip class="box-item" effect="customized" :content="item.outCode + '　' + item.name"
                    placement="right">
                    <div style="
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                      ">
                      {{ item.outCode + '　' + item.name }}
                    </div>
                  </el-tooltip>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="领用编号" prop="outCode" align="center" />
          <el-table-column label="纯度" prop="con" align="center">
            <template #default="scope">
              <el-input clearable maxlength="100" v-model="scope.row.con" />
            </template>
          </el-table-column>
          <el-table-column label="入库日期" prop="outDate" align="center">
            <template #default="scope">
              {{ scope.row.outDate }}
            </template>
          </el-table-column>
          <el-table-column label="取样量" prop="qyl" align="center">
            <template #default="scope">
              <el-input-number clearable v-model="scope.row.qyl" :min="1" style="width: 100%"
                controls-position="right"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="取样量单位" prop="qylUnit" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.qylUnit" placeholder="请选择" clearable filterable>
                <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName" :value="item.unitId">
                  <span v-html="transformation(item.unitName)"></span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="success" @click="delectBzwzList(scope.$index, 0)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-row>
          <p class="pinformation">检测项目列表</p>
          <p class="totalStyle">
            共 {{ form.selfSampleJcxmList.length }} 条数据
          </p>
          <el-row style="padding-bottom: 5px; margin-left: 20px">
            <el-button link icon="Plus" @click="handleJcxmList">新增</el-button>
            <el-button link @click="delectJcxmList(a, 1)" :disabled="ids2">批量删除</el-button>
          </el-row>
        </el-row>
        <el-table :data="form.selfSampleJcxmList" @selection-change="handleJcxmSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="检测项目" prop="bucketId" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.bucketId" clearable filterable remote reserve-keyword remote-show-suffix
                :remote-method="remoteMethod1" @click="getIndex(scope.$index)" :loading="loading1" style="width: 100%">
                <el-option v-for="item in scope.row.jcxmList" :key="item.bucketId" :value="item.bucketId"
                  :label="item.jcxmName">
                  <span v-html="transformation(item.jcxmName)"></span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="浓度值" prop="con" align="center">
            <template #default="scope">
              <el-input-number clearable v-model="scope.row.con" :min="1" style="width: 100%" controls-position="right" />
            </template>
          </el-table-column>
          <el-table-column label="浓度值单位" prop="conUnit" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.conUnit" placeholder="" clearable filterable>
                <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName" :value="item.unitId">
                  <span v-html="transformation(item.unitName)"></span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="success" @click="delectJcxmList(scope.$index, 0)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="saveZzyp">保 存</el-button>
          <el-button type="danger" @click="rkOrYyOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :class="'el-dialog-theme3'" :title="upload.title" v-model="upload.open" width="400px"
      append-to-body draggable :close-on-click-modal="false">
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-error="handleUploadError"
        :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="success" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="submitFileForm">确 定</el-button>
          <el-button type="danger" @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BzwzOutin">
import onlinePreview from "@/components/onlinePreview/index.vue";
import {
  listLedger,
  sampleList,
  delSampleList,
  zzypViewForm,
  addSample,
  getJcxmList,
  getBzwzList,
  getRowForm,
  getTpCodeList,
  getTpType,
} from "@/api/resource/selfSampleLedger";
import { getCurrentTime } from "@/api/common";
import { getSeqId } from "@/api/common";
import { getUnitList } from "@/api/store/unit";
import { listUser } from "@/api/contract/check";
import { nextTick } from "vue";

const { proxy } = getCurrentInstance();
const {
  sys_self_sample_type,
  sys_bzwz_gslb,
  sys_bzwz_gqlx,
  sys_bzwz_jcxm_type,
} = proxy.useDict(
  "sys_self_sample_type",
  "sys_bzwz_gslb",
  "sys_bzwz_gqlx",
  "sys_bzwz_jcxm_type"
);

const outTable = ref([]);
const multiplexTable = ref([]);
const jcxmList = ref([]);
const jcxmOpen = ref(false);
const rkOrYyOpen = ref(false);
const rkOrYyTitle = ref("");
const title = ref("查看检测项目");
const dateRange = ref([]);
const data = reactive({
  form: { selfSampleBzwzList: [], selfSampleJcxmList: [], params: {} },
  queryParams: {
    pageNum: 1, // 当前页数
    pageSize: 10, // 当前页数据条数
    isLike: "0",
    selfAdminId: -1,
    isSingle: -1,
  },
  rules: {
    sampleName: [
      { required: true, message: "自制样品名称不能为空", trigger: "blur" },
    ],
    drtjUnit: [
      { required: true, message: "定容体积单位不能为空", trigger: "blur" },
    ],
    drtj: [{ required: true, message: "定容体积不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);
// 编号配置
const serialTypeId = ref(40);
const onlinePreviewRef = ref(null);
function emitForm(val) {
  form.value.params["serialData"] = val;
}

const heightParams = ref([{ tableName: "main", bottomHeight: 21 }]);

function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}

const bzwzList = ref([]);
getBzwzList().then((res) => {
  bzwzList.value = res.data;
});
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  })
})
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

const total = ref(0);
function getList() {
  listLedger(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (res) => {
      outTable.value = res.rows;
      total.value = res.total;
    }
  );
}
getList();

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.isLike = "0";
  dateRange.value = [];
  handleQuery();
}

function jcxmCountClick(row) {
  sampleList({ sampleId: row }).then((res) => {
    multiplexTable.value = res.data;
    jcxmOpen.value = true;
  });
}

function closedDialog() {
  multiplexTable.value = [];
}

function delBzwz(sampleId) {
  proxy.$modal
    .confirm("是否确认删除该条记录？")
    .then(function () {
      delSampleList(sampleId).then((res) => {
        proxy.$modal.msgSuccess("删除成功");
        getList();
      });
    })
    .catch(() => { });
}

function xqZzyp(sampleId, isOpen) {
  zzypViewForm(sampleId).then((res) => {
    form.value = res.data;
    form.value.selfSampleJcxmList.forEach(item => {
      item.jcxmList = [{ bucketId: item.bucketId, jcxmName: item.jcxmName }]
    })
    if (isOpen == 1) {
      rkOrYyOpen.value = true;
      rkOrYyTitle.value = "引用自制样品";
      form.value.isDel = true;
      delete form.value.useDrtj;
      delete form.value.sampleCode;
      form.value.params = {};
      form.value.selfSampleBzwzList.forEach((item, index) => {
        getSeqId().then((res) => {
          form.value.selfSampleBzwzList[index].sBId = res.data;
        });
      });
      form.value.selfSampleJcxmList.forEach((item, index) => {
        getSeqId().then((res) => {
          form.value.selfSampleJcxmList[index].sJId = res.data;
        });
      });
    } else if (isOpen == 3) {
      rkOrYyOpen.value = true;
      rkOrYyTitle.value = "编辑自制样品";
    }
  });
}

function closedXqDialog() {
  form.value = {
    selfSampleBzwzList: [],
    selfSampleJcxmList: [],
    params: {},
  };
}

function singleAdd() {
  getCurrentTime().then((res) => {
    form.value.createDate = res.data;
  });
  rkOrYyOpen.value = true;
  rkOrYyTitle.value = "自制样品入库";
}

function saveZzyp() {
  proxy.$refs["rkOrYyRef"].validate((valid) => {
    if (valid) {
      if (
        form.value.selfSampleJcxmList.length &&
        form.value.selfSampleBzwzList.length
      ) {
        for (const item of form.value.selfSampleJcxmList) {
          if (!item.bucketId || !item.con || !item.conUnit) {
            proxy.$modal.msgError("请将检测项目列表数据补充完整");
            return false;
          }
        }

        for (const item of form.value.selfSampleBzwzList) {
          if (!item.outId) {
            proxy.$modal.msgError("选择参与物质必选");
            return false;
          }
        }

        if (form.value.isDel) {
          delete form.value.sampleId;
        }
        addSample(form.value).then((res) => {
          rkOrYyOpen.value = false;
          proxy.$modal.msgSuccess(res.msg);
          getList();
        });
      } else {
        proxy.$modal.msgError("检测项目列表不能为空");
      }
    }
  });
}

function handleJcxmList() {
  getSeqId().then((res) => {
    form.value.selfSampleJcxmList.push({ sJId: res.data });
  });
}

function handleBzwzList() {
  getSeqId().then((res) => {
    form.value.selfSampleBzwzList.push({ sBId: res.data, bzwzOut: {} });
  });
}

const tempBzwzList = ref([]);
const ids = ref(false);
const ids2 = ref(false);
function handleBzwzSelectionChange(selection) {
  ids.value = selection.length ? false : true;
  tempBzwzList.value = form.value.selfSampleBzwzList.filter((row) => {
    return selection.indexOf(row) == -1;
  });
}

const tempJcxmList = ref([]);
function handleJcxmSelectionChange(selection) {
  ids2.value = selection.length ? false : true;
  tempJcxmList.value = form.value.selfSampleJcxmList.filter((row) => {
    return selection.indexOf(row) == -1;
  });
}

function delectBzwzList(row, bs) {
  proxy.$modal
    .confirm("是否确认该条删除数据项？")
    .then(function () {
      if (bs) {
        form.value.selfSampleBzwzList = tempBzwzList.value;
      } else {
        form.value.selfSampleBzwzList.splice(row, 1);
      }
    })
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function delectJcxmList(row, bs) {
  proxy.$modal
    .confirm("是否确认该条删除数据项？")
    .then(function () {
      if (bs) {
        form.value.selfSampleJcxmList = tempJcxmList.value;
      } else {
        form.value.selfSampleJcxmList.splice(row, 1);
      }
    })
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

const unitList = ref([]);
getUnitList({ unitGroup: 0 }).then((res) => {
  getUnitList({ unitGroup: 5 }).then((res1) => {
    unitList.value = Object.assign(res1.data, res.data);
  });
});

function handleSelChange(selection) {
  multiplexTable.value = selection;
}

const loading = ref(false);
const loading1 = ref(false);

function remoteMethod(val) {
  if (val) {
    loading.value = true;
    setTimeout(() => {
      getJcxmList({ jcxmName: val }).then((res) => {
        loading.value = false;
        jcxmList.value = res.rows;
      });
    }, 200);
  } else {
    jcxmList.value = [];
  }
}

const listIndex = ref(0);
function getIndex(index) {
  listIndex.value = index;
}

function remoteMethod1(val) {
  if (val) {
    loading1.value = true;
    setTimeout(() => {
      getJcxmList({ jcxmName: val }).then((res) => {
        loading1.value = false;
        form.value.selfSampleJcxmList[listIndex.value].jcxmList = res.rows;
      });
    }, 200);
  } else {
    form.value.selfSampleJcxmList[listIndex.value].jcxmList = [];
  }
}

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [{ tableName: "main", bottomHeight: 73 }];
    } else {
      heightParams.value = [{ tableName: "main", bottomHeight: 21 }];
    }
    getTableHeight();
  }
);

function transformation(row) {
  const a = proxy.getSupAndSub(row);
  return a;
}

function outCodeChange(scope) {
  if (scope.row.outId) {
    form.value.selfSampleBzwzList[scope.$index].outId = scope.row.outId;
    form.value.selfSampleBzwzList[scope.$index].outSource = proxy.getItemByArray(
      bzwzList.value,
      "outId",
      scope.row.outId,
      "outSource"
    );
    getRowForm({ outId: scope.row.outId, outSource: form.value.selfSampleBzwzList[scope.$index].outSource }).then(
      (res) => {
        form.value.selfSampleBzwzList[scope.$index].outDate =
          proxy.parseTime(res.data.createDate, "{y}-{m}-{d}")
        form.value.selfSampleBzwzList[scope.$index].outCode =
          res.data.outCode
      }
    );
  } else {
    form.value.selfSampleBzwzList[scope.$index].outId = "";
    form.value.selfSampleBzwzList[scope.$index].outDate = "";
    form.value.selfSampleBzwzList[scope.$index].outCode = "";
  }
}

const tpCodeList = ref([]);
getTpCodeList({ typeId: 2 }).then((res) => {
  tpCodeList.value = res.data;
});

function tpCodeChange() {
  getTpType(form.value.tpCode).then((res) => {
    form.value.tpXh = res.data.code;
  });
}

function getConUnitHtml(conUnit) {
  return proxy.getItemByArray(unitList.value, "unitId", conUnit, "unitName");
}

const userList = ref([]);
listUser().then((res) => {
  userList.value = res.data;
});

function pickerChange(val) {
  let createDate = form.value.createDate;
  let yxDate = form.value.yxDate;
  if (yxDate.split("-")[0] < createDate.split("-")[0]) {
    form.value.yxDate = form.value.createDate;
  } else {
    if (yxDate.split("-")[0] === createDate.split("-")[0]) {
      if (yxDate.split("-")[1] < createDate.split("-")[1]) {
        form.value.yxDate = form.value.createDate;
      } else {
        if (yxDate.split("-")[1] === createDate.split("-")[1]) {
          if (yxDate.split("-")[2] < createDate.split("-")[2]) {
            form.value.yxDate = form.value.createDate;
          }
        }
      }
    }
  }
}

// -------------------导入模板逻辑-------------------
import { getToken } from "@/utils/auth";
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/resource/sample/importData",
});

/** 导入按钮操作 */
function handleImport() {
  upload.title = "自制样品入库登记导入";
  upload.open = true;
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
    response.msg +
    "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "/resource/sample/export",
    {
      ...queryParams.value,
    },
    `自制样品入库登记表_${new Date().getTime()}.xlsx`
  );
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download(
    "/resource/sample/importTemplate",
    {},
    `自制样品模板_${new Date().getTime()}.xlsx`
  );
}

// 上传失败
function handleUploadError(err) {
  upload.isUploading = false;
  proxy.$modal.msgError("导入数据失败，原因：" + err.message);
}
</script>

<style lang="scss" scoped>
.el-radio {
  margin-right: 5px;
}
</style>
